package com.mayikt.classloader;

import com.mayikt.service.OrderService;

import java.io.File;

/**
 * @ClassName Test014
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class Test014 {
    private static long mayiktStartTime;

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        MayiktClassLoader mayiktClassLoader = new MayiktClassLoader();
        mayiktClassLoader.setFileObject(new File("E:\\code\\OrderServiceImpl.class"));
        Class<?> aClass = mayiktClassLoader.loadClass("com.mayikt.service.impl.OrderServiceImpl");
        OrderService orderService1 = (OrderService) aClass.newInstance();
        System.out.println(orderService1.addOrder());
        // 热部署功能，当我们的class文件发生变化的时候，不需要人为重启服务器
        File file = new File("E:\\code\\OrderServiceImpl.class");
        mayiktStartTime = file.lastModified();
        new Thread(() -> {

            while (true) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 检测该class文件是否有发生变化
                long endTime = file.lastModified();
                if (endTime != mayiktStartTime) {
                    System.out.println("该class文件发生了变化");
                    // 文件发生变化
                    try {
                        MayiktClassLoader mayiktClassLoader1 = new MayiktClassLoader();
                        mayiktClassLoader1.setFileObject(new File("E:\\code\\OrderServiceImpl.class"));
                        Class<?> bClass =
                                mayiktClassLoader1.loadClass("com.mayikt.service.impl.OrderServiceImpl");
                        OrderService orderService2 = (OrderService) bClass.newInstance();
                        System.out.println(orderService2.addOrder());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mayiktStartTime = endTime;
                }
            }
        }).start();

    }
}
